clear all;
% Save current directory
currentFolder = pwd; 
%% INITIAL 
% Define the subfolder path
subfolder = fullfile(fileparts(currentFolder), 'functionsRA'); 

% Loop over numbers 1 to 8
for i = 1:8
    fprintf('Iteration %d starting...\n', i); % Display progress
    
    % Change directory to the subfolder
    cd(subfolder);

    % Assign the iteration number to a variable in the base workspace
    assignin('base', 'iterationNumber', i); 

    % Run the scripts with error handling
    try
        run('InitialUS.m');  
        run('InitialEZ.m');  
    catch ME
        fprintf('Error in iteration %d: %s\n', i, ME.message);
    end
    
    % Return to the original directory
    cd(currentFolder);
end

fprintf('All iterations completed.\n');

% Define input folder
subfolder = fullfile(fileparts(currentFolder), 'input'); 

% File paths
ezFile = fullfile(subfolder, 'prob_avginfl_monthly_EZ.xlsx');
usFile = fullfile(subfolder, 'prob_avginfl_monthly_US.xlsx');
baselineFile = 'prob_avginfl_monthly.xlsx';

% Column names
columnNames = {'year', 'month', 'Bin1', 'Bin2', 'Bin3', 'Bin4', 'Bin5', 'Bin6', 'Bin7', 'Bin8', 'Baseline'};

% Generate Year and Month columns
years = repelem(2011:2023, 12)'; % 2011-2023, each repeated 12 times
months = repmat((1:12)', 13, 1);  % Months repeating for each year

% Add 2024 (only first 10 months)
years = [years; repmat(2024, 10, 1)];
months = [months; (1:10)'];

% Create an empty matrix for the Bin data (all NaNs for now)
binData = nan(length(years), 9); % 9 bins (Bin1 to Bin8 + Baseline)

% Create initial table
T = table(years, months, binData(:,1), binData(:,2), binData(:,3), binData(:,4), ...
           binData(:,5), binData(:,6), binData(:,7), binData(:,8), binData(:,9), ...
           'VariableNames', columnNames);

% Write initial empty table to EZ and US files
writetable(T, ezFile, 'Sheet', 'Bins');
writetable(T, usFile, 'Sheet', 'Bins');
fprintf('Initialized "Bins" sheets for EZ and US.\n');

% ==========================
%    PROCESS EUROPE (EZ)
% ==========================
fprintf('Processing EZ file...\n');
binsData_EZ = readtable(ezFile, 'Sheet', 'Bins');

for i = 1:8
    sheetName = sprintf('EZ_model_101_month%d', i);
    rawData = readtable(ezFile, 'Sheet', sheetName, 'Range', 'D3:D168');
    
    if height(rawData) == 166
        binsData_EZ.(sprintf('Bin%d', i)) = rawData{:,1}; % Convert to numeric
    else
        fprintf('Warning: Data size mismatch in %s (Sheet: %s).\n', ezFile, sheetName);
    end
end

% Read EZ baseline data
baselineSheet = 'EZ_model_101_month';
baselineData = readtable(baselineFile, 'Sheet', baselineSheet, 'Range', 'D3:D168');

if height(baselineData) == 166
    binsData_EZ.Baseline = baselineData{:,1};
else
    fprintf('Warning: Baseline data size mismatch for EZ.\n');
end

% Save updated EZ file
writetable(binsData_EZ, ezFile, 'Sheet', 'Bins');
fprintf('EZ processing completed.\n');

% ==========================
%    PROCESS US
% ==========================
fprintf('Processing US file...\n');
binsData_US = readtable(usFile, 'Sheet', 'Bins');

for i = 1:8
    sheetName = sprintf('US_model_101_month%d', i);
    rawData = readtable(usFile, 'Sheet', sheetName, 'Range', 'D3:D168');
    
    if height(rawData) == 166
        binsData_US.(sprintf('Bin%d', i)) = rawData{:,1}; % Convert to numeric
    else
        fprintf('Warning: Data size mismatch in %s (Sheet: %s).\n', usFile, sheetName);
    end
end

% Read US baseline data
baselineSheet = 'US_model_101_month';
baselineData = readtable(baselineFile, 'Sheet', baselineSheet, 'Range', 'D3:D168');

if height(baselineData) == 166
    binsData_US.Baseline = baselineData{:,1};
else
    fprintf('Warning: Baseline data size mismatch for US.\n');
end

% Save updated US file
writetable(binsData_US, usFile, 'Sheet', 'Bins');
fprintf('US processing completed.\n');

fprintf('All files updated successfully.\n');



% ==========================
%    RENAME FILES
% ==========================
newEzFile = fullfile(subfolder, 'Initial_EZ.xlsx');
newUsFile = fullfile(subfolder, 'Initial_US.xlsx');

try
    movefile(ezFile, newEzFile);
    fprintf('Renamed %s to %s.\n', ezFile, newEzFile);
catch ME
    fprintf('Error renaming EZ file: %s\n', ME.message);
end

try
    movefile(usFile, newUsFile);
    fprintf('Renamed %s to %s.\n', usFile, newUsFile);
catch ME
    fprintf('Error renaming US file: %s\n', ME.message);
end

fprintf('All files updated and renamed successfully.\n');




%% CONDITIONAL
currentFolder = pwd; 

subfolder = fullfile(fileparts(currentFolder), 'functionsRA'); 
   run(fullfile(subfolder,'Conditional_Prob.m'));  
 fprintf('Processed Conditional EZ.');
currentFolder = pwd; 
subfolder = fullfile(fileparts(currentFolder),'functionsRA'); 

   run(fullfile(subfolder,'Conditional_Prob_US.m'));  
 fprintf('Processing Conditional US.');


currentFolder = pwd; 

subfolder = fullfile(fileparts(currentFolder), 'input'); 


% Define the file names
% Original Excel file names (to be read)
file_final_original = fullfile(subfolder, 'myData_Final.xlsx');
file_usa_original   = fullfile(subfolder, 'myData_USA_FINAL.xlsx');

% New Excel file names (to be written)
file_ez_new = fullfile(subfolder, 'Conditional_EZ_new.xlsx');
file_us_new = fullfile(subfolder, 'Conditional_US_new.xlsx');

% --- Update myData_Final.xlsx and save as Conditional_EZ_new.xlsx ---
% Read the existing Excel file into a cell array.
data_final = readcell(file_final_original);

% Determine the number of columns.
[~, nCols] = size(data_final);

% Create a new header row (filling columns A–C).
newHeader = cell(1, nCols);
newHeader{1} = 'Year1';
newHeader{2} = 'Year2';
newHeader{3} = 'Year0';

% Insert the header row at the top (pushing the rest of the data down).
data_final = [newHeader; data_final];

% --- Modify column D ---
% Set cell D1 to 'Date'
data_final{1,4} = 'Date';  
% For rows D2 to D47, assign sequential numbers 732 to 777.
for row = 2:47
    data_final{row,4} = row + 730;  % When row = 2, value = 732; when row = 47, value = 777.
end

% Replace any missing values with an empty string (since writecell cannot handle 'missing').
data_final(cellfun(@(x) isa(x, 'missing'), data_final)) = {''};

% Write the modified data to the new Excel file.
writecell(data_final, file_ez_new);

%--- Update myData_USA_FINAL.xlsx and save as Conditional_US_new.xlsx ---
% Read the USA Excel file into a cell array.
data_usa = readcell(file_usa_original);

% Get the number of columns.
[~, nCols] = size(data_usa);

% Create and insert the new header row.
newHeader = cell(1, nCols);
newHeader{1} = 'Year1';
newHeader{2} = 'Year2';
newHeader{3} = 'Year0';
data_usa = [newHeader; data_usa];

% --- Modify column D ---
% Set D1 to 'Date'
data_usa{1,4} = 'Date';
% For rows D2 to D47, assign sequential numbers 732 to 777.
for row = 2:47
    data_usa{row,4} = row + 730;
end

% --- Modify column E ---
% For rows E2 to E47, assign sequential numbers 121 to 166.
for row = 2:47
    data_usa{row,5} = row + 119;  % When row = 2, value = 121; when row = 47, value = 166.
end

% Replace any missing values with an empty string.
data_usa(cellfun(@(x) isa(x, 'missing'), data_usa)) = {''};

% Write the modified data back to the new Excel file.
writecell(data_usa, file_us_new);



%%
currentFolder = pwd; 

stataDir = fullfile(fileparts(currentFolder), 'functionsRA'); 

% Define paths to your Stata .do file
doFile1 = fullfile(stataDir, 'Initial.do');
doFile2= fullfile(stataDir, 'Conditional.do');

% Define Stata executable path (modify according to your installation)
stataPath = '"C:\Program Files\Stata18\StataSE-64.exe"';  
% Ensure MATLAB switches to the correct directory before launching Stata
cd(stataDir);

% Run the first .do file
command1 = sprintf('%s /e do "%s"', stataPath, doFile1);
status1 = system(command1);

% Check if the first script ran successfully
if status1 == 0
    disp('Stata Initial script ran successfully.');
else
    disp('Error running Stata EZ script.');
end


% Run the second .do file
command2 = sprintf('%s /e do "%s"', stataPath, doFile2);
status2 = system(command2);

% Check if the first script ran successfully
if status2 == 0
    disp('Stata Conditional script ran successfully.');
else
    disp('Error running Stata US script.');
end
